import {useStore} from '@/stores'

import {deleteAsset, loadAssetLevelPage, loadMoveAssetPage, moveAsset, saveAsset} from '@/apis/sop'
import {SERVERS} from "@/stores/conf";
import {useTerminal} from '@/utils/sop/UseTerminal';
import {handleResult} from "@/utils/SystemUtil";

export function useAssetOp(entry: any) {
  const store = useStore();
  const {productCode} = useTerminal(entry.name);

  const getTargetId = (id: string) => {
    if (id) {
      return id;
    } else if (SERVERS.REALM === entry.server) {
      return store.getCurrentPlatform().realmId;
    } else {
      return store.getCurrentPlatform().id;
    }
  }

  const doLoadAsset = async (targetId: string, type: string, params: any, ) => {
    const result = await loadAssetLevelPage({
      server: entry.server,
      targetId: getTargetId(targetId),
      assetType: type,
      parentId: params.parentId,
      productCode: productCode(),
      ...params
    });

    if (result && result.data) {
      handleResult(result.data, ['exist']);
    }

    return result;
  }

  const doSaveAsset = async (targetId: string, asset: any, ) => {
    return await saveAsset({
      server: entry.server,
      targetId: getTargetId(targetId),
      asset: asset,
      productCode: productCode(),
    });
  }

  const doDeleteAsset = async (targetId: string, asset: any, ) => {
    return await deleteAsset({
      server: entry.server,
      targetId: getTargetId(targetId),
      productCode: productCode(),
      assetId: asset.id,
      assetType: asset.type,
    });
  }

  /**
   * 把资源移动到目标资源下（改变其父节点）
   * @param targetId
   * @param param {
   *     server: '',
   *     targetId: '',
   *     assetId: '',
   *     assetType: '',
   *     parentId: '',
   * }
   */
  const doMoveAsset = async (targetId: string, param: any) => {
    const p: any = {
      server: entry.server,
      targetId: getTargetId(targetId),
      productCode: productCode(),
      ...param,
    }
    return await moveAsset(p);
  }

  /**
   * 读取可以移动到的目标资源列表
   * @param targetId
   * @param param {
   *     current: 1,
   *     pageSize: 10,
   *     server: '',
   *     targetId: '',
   *     assetId: '',
   *     assetType: '',
   *     name: '',
   * }
   * @returns [{
   *     id: '',
   *     name: '',
   *     code: '',
   *     type: '',
   *     createTime: '',
   * }]
   */
  const doLoadMoveAsset = async (targetId: string, param: any) => {
    const p: any = {
      server: entry.server,
      targetId: getTargetId(targetId),
      productCode: productCode(),
      ...param,
    };
    return await loadMoveAssetPage(p);
  }

  return {
    doLoadAsset,
    doSaveAsset,
    doDeleteAsset,
    doMoveAsset,
    doLoadMoveAsset
  }
}
